import React from 'react';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Menu, Dropdown, Card, Col, Row, Button, Select, Modal, DatePicker, Divider } from 'antd';
import { connect } from 'dva';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import StandardTable from '@/components/StandardTable';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const FormItem = Form.Item;

const { RangePicker } = DatePicker;
const { confirm } = Modal;

@connect(({ inservicematerial, loading }) => ({
  inservicematerial,
  loading: loading.models.inservicematerial,
}))
@Form.create()
class InserviceMaterial extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
    };
    this.tableSearchLayout = {
      labelCol: {
        lg: {
          span: 7,
        },
        xl: {
          span: 6,
        },
        xxl: {
          span: 4,
        },
        md: {
          span: 7,
        },
      },
      wrapperCol: {
        xxl: {
          span: 17,
        },
        md: {
          span: 17,
        },
      },
    };
  }

  componentDidMount = () => {
    const {
      location,
      inservicematerial: {
        data: { pagination },
      },
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    }
    this.getList(pagination.current, pagination.pageSize);
    this.changeArea();
  };

  // 地区
  changeArea = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/fetchAreaList',
      payload: {},
    });
  };


  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.setFieldsValue({
      dateArr: null,
    });
  };

  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'inservicematerial/updateModelData',
        payload: { formFieldsValue: fieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'dateArr') {
          formFieldsValue.startTime =
            fieldsValue.dateArr && fieldsValue.dateArr[0].format('YYYY-MM-DD');
          formFieldsValue.endTime =
            fieldsValue.dateArr && fieldsValue.dateArr[1].format('YYYY-MM-DD');
          delete formFieldsValue[key];
        }
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
      });
      const page = { currentPage, pageSizes: pageSize };
      const values = {
        mat: { ...formFieldsValue },
        page,
      };
      dispatch({
        type: 'inservicematerial/fetchList',
        payload: values,
      });
    });
  };

  // 列表模板
  deleteMat = (matPkgId, vno) => {
    const { dispatch } = this.props;
    confirm({
      title: '你确定要删除此条信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'inservicematerial/fetchDelete',
          payload: { matPkgId, vno },
        });
      },
      onCancel() {},
    });
  };

  toggleForm = () => {
    const {
      inservicematerial: { expandForm },
      dispatch,
    } = this.props;
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 在职材料
  addmaterial = () => {
    router.push('/materialmanagement/inservicematerial/add');
  };

  linkRoute = (id, path) =>
    id
      ? router.push(`/materialmanagement/inservicematerial/${path}?id=${id}`)
      : router.push(`/materialmanagement/${path}`);

  matChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/fetchSerTypeList',
      payload: { serType: value },
    });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    await this.resetSearch();
    await this.getList();

    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      inservicematerial: { formFieldsValue, matList, areaList },
    } = this.props;

    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={8}>
            <FormItem label="服务类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('serType', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.serType,
              })(
                <DictCode
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  dictType="ENTRY_SER_TYPE"
                  onSelect={this.matChange}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="材料类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('serTypeId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.serTypeId,
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                  placeholder="请选择材料类型"
                >
                  {matList.map(value => (
                    <Option key={value.serTypeId}>{value.serTypeIdName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="地区" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.areaId,
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  placeholder="请选择地区"
                >
                  {areaList.map(value => (
                    <Option key={value.areaId}>{value.areaName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={8}>
            <FormItem label="创建时间:" {...this.tableSearchLayout}>
              {getFieldDecorator('dateArr', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.dateArr,
              })(
                <RangePicker
                  format="YYYY-MM-DD"
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {
      inservicematerial: { expandForm },
    } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      inservicematerial: { formFieldsValue, matList },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={8}>
            <FormItem label="服务类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('serType', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.serType,
              })(
                <DictCode
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  dictType="ENTRY_SER_TYPE"
                  onSelect={this.matChange}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="材料类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('serTypeId', {
                rules: [{ required: false }],
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                  placeholder="请选择材料类型"
                >
                  {matList.map(value => (
                    <Option key={value.serTypeId}>{value.serTypeIdName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      inservicematerial: { data, loading },
    } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const moreMenu = record => (
      <Menu>
        <Menu.Item key="del" onClick={() => this.linkRoute(record.matPkgId, 'update')}>
          修改
        </Menu.Item>
        <Menu.Item key="del" onClick={() => this.deleteMat(record.matPkgId, record.vno)}>
          删除
        </Menu.Item>
      </Menu>
    );
    const columns = [
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '材料类型',
        dataIndex: 'serTypeIdName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.linkRoute(record.matPkgId, 'detail')}>查看</a>
            <Divider type="vertical" />
            <Dropdown overlay={moreMenu(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <Button onClick={this.addmaterial} type="primary" style={{ margin: '12px 0 16px' }}>
            <PlusOutlined /> 新增
          </Button>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={data}
            rowKey="matPkgId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default InserviceMaterial;
